package com.mxw.account.controller;

import cn.hutool.json.JSONUtil;
import com.mxw.account.dto.AccountDTO;
import com.mxw.commons.restful.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * @Description
 * @Author RingKo
 * @Date 2021/8/23 22:13
 * @Version 1.0
 */
@Slf4j
@RestController
@Validated
public class UploadTestController {
    /**
     * @Description: 文件上传测试接口
     */
    @PostMapping("/account/upload/test")
    public Result<Void> uploadTest(@RequestPart("file") @NotNull List<MultipartFile> files, @RequestPart("account") @Valid AccountDTO accountDTO, @RequestParam String testdata) {
        for (MultipartFile file : files) {
            log.info(file.getOriginalFilename());
        }
        log.info(accountDTO.toString());
        log.info(testdata);
        return Result.respond();
    }

    /**
     * @Description: 文件上传测试接口2
     */
    @PostMapping("/account/upload/test2")
    public Result<Void> uploadTest2(@RequestParam("file") @NotNull List<MultipartFile> files, @RequestParam("account") String accountJsonString) throws Exception {
        for (MultipartFile file : files) {
            log.info(file.getOriginalFilename());
            byte[] bytes = file.getBytes();
            OutputStream os = new FileOutputStream(file.getOriginalFilename());
            for (int x = 0; x < bytes.length; x++) {
                os.write(bytes[x]); // writes the bytes
            }
            os.close();
        }
        AccountDTO accountDTO = JSONUtil.toBean(accountJsonString, AccountDTO.class);
        log.info(accountDTO.toString());
        return Result.respond();
    }
}
